package utils;

import org.apache.commons.text.TextStringBuilder;

/**
 * 特殊字符替换工具类
 */
public class SpecialCodeReplaceUtil {

    public static String doReplace(String plainTxt){
        if(plainTxt == null){
            return null;
        }

        TextStringBuilder stringBuilder = new TextStringBuilder(120);

        // 全角转半角
        char[] plainChar = plainTxt.toCharArray();
        for(int i=0; i<plainChar.length; i++){
            if(plainChar[i] == 12288){
                plainChar[i] = ' ';
            }else if(plainChar[i] >= 65281 && plainChar[i] <= 65374){
                plainChar[i] = (char) (plainChar[i] - 65248);
            }
        }

        stringBuilder.append(plainChar);

        // 优先转义，因为下面转义后的每个转义字符后都包含“;”、“&”、“#”
        // ;符号转义
        stringBuilder.replaceAll(";","&#59;");
        // &符号转义
        stringBuilder.replaceAll("&","&#38;");
        // #符号转义
        stringBuilder.replaceAll("#","&#35;");

        // ~符号转义，（存在争议）
        stringBuilder.replaceAll("~","&#126;");
        // `符号转义
        stringBuilder.replaceAll("`","&#96;");
        // !符号转义
        stringBuilder.replaceAll("!","&#33;");
        // @符号转义
        stringBuilder.replaceAll("@","&#64;");
        // $符号转义
        stringBuilder.replaceAll("$","&#36;");
        // %符号转义
        stringBuilder.replaceAll("%","&#37;");
        // ^符号转义
        stringBuilder.replaceAll("^","&#94;");
        // *符号转义
        stringBuilder.replaceAll("*","&#42;");
        // (符号转义
        stringBuilder.replaceAll("(","&#40;");
        // )符号转义
        stringBuilder.replaceAll(")","&#41;");
        // -符号转义
        stringBuilder.replaceAll("-","&#45;");
        // _符号转义
        stringBuilder.replaceAll("_","&#95;");
        // =符号转义
        stringBuilder.replaceAll("=","&#61;");
        // +符号转义
        stringBuilder.replaceAll("+","&#43;");
        // {符号转义
        stringBuilder.replaceAll("{","&#123;");
        // [符号转义
        stringBuilder.replaceAll("[","&#91;");
        // }符号转义
        stringBuilder.replaceAll("}","&#125;");
        // ]符号转义
        stringBuilder.replaceAll("]","&#93;");
        // \符号转义
        stringBuilder.replaceAll("\\","&#92;");
        // |符号转义
        stringBuilder.replaceAll("|","&#124;");
        // :符号转义
        stringBuilder.replaceAll(":","&#58;");
        // '符号转义
        stringBuilder.replaceAll("'","&#39;");
        // "符号转义
        stringBuilder.replaceAll("\"","&#34;");
        // ,符号转义
        stringBuilder.replaceAll(",","&#44;");
        // <符号转义
        stringBuilder.replaceAll("<","&#60;");
        // .符号转义
        stringBuilder.replaceAll(".","&#46;");
        // >符号转义
        stringBuilder.replaceAll(">","&#62;");
        // /符号转义
        stringBuilder.replaceAll("/","&#47;");
        // ?符号转义
        stringBuilder.replaceAll("?","&#63;");
        // 空格转义
        stringBuilder.replaceAll(" ","&#32;");

        return stringBuilder.toString();
    }
}
